package com.bootdo.common.task;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import org.apache.batik.bridge.UserAgent;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import com.bootdo.common.service.DistConfigValueService;
import com.bootdo.hjh.cache.GroupTree;
import com.bootdo.hjh.cache.MemberCache;
import com.bootdo.hjh.cache.Node;
import com.bootdo.hjh.cache.NodeInfo;
import com.bootdo.oa.domain.Response;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;

@Component
public class UserUpgradeJob implements Job{

	private static final Logger LOGGER = LoggerFactory.getLogger(CashJob.class);
	@Autowired
	SimpMessagingTemplate template;
	@Autowired
	private UserService userService;

	@Autowired
	private DistConfigValueService distConfigValueService;

	@Autowired
	private MemberCache memberCache;


    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
    		// 查找所有的叶子节点
		List<Node> nodes = allLeaf();
		for (Node node : nodes) {
			if (node != null) {
				userService.upgradeTrigger(node.getInfo().getUserId());
			}
		}

		LOGGER.info("检查所有用户升级跑批业务结束");
    		template.convertAndSend("/topic/getResponse", new Response("检查用户升级完成" ));
    }


	private List<Node> allLeaf() {
    	List<Node> allLeaf = new ArrayList<>();
		Collection<GroupTree> groupTrees = memberCache.getGroup().getCache().values();
		if (groupTrees == null || groupTrees.isEmpty()) {
			return allLeaf;
		}

		for (GroupTree groupTree : groupTrees) {
			Queue<Node> queue = new LinkedList<>();
			Node tmp = groupTree.getRoot();
			queue.offer(tmp);
			while (!queue.isEmpty()) {
				// 出队
				tmp = queue.poll();
				List<Node> recommendNodeList = tmp.getRecommendNodeList();
				if (recommendNodeList == null || recommendNodeList.isEmpty()) {
					allLeaf.add(tmp);
					continue;
				}
				for (Node node : recommendNodeList) {
					// 入队
					queue.offer(node);
				}
			}
		}
		return allLeaf;
	}
}
